import { DatePicker } from '@/components/AntdProxy';
import Crud from '@/components/Crud';
import {
  DriverSelect,
  GroupTreeSelect,
  LineSelect,
  VehicleSelect,
} from '@/components/CustomForm';
import { BOOLEAN_MAP, BOOLEAN_OPTIONS } from '@/constants/enums';
import useMaterial from '@/hooks/useMaterial';
import TripDetail from '@/pages/report/trip-manage/components/Detail';
import request from '@/utils/request';
import {
  DeleteOutlined,
  DollarOutlined,
  DownloadOutlined,
  FileTextOutlined,
  PlusOutlined,
  TruckOutlined,
} from '@ant-design/icons';
import { Button, Form, Input, message, Modal, Select, Space } from 'antd';
import dayjs from 'dayjs';
import { useRef, useState } from 'react';
import Detail from './components/Detail';
import Save from './components/Save';

const ADDITIONAL_FIELDS = [
  {
    label: '组织',
    name: 'groupId',
    children: <GroupTreeSelect placeholder="请选择组织" />,
  },
  {
    label: '车辆',
    name: 'vehicleId',
    children: <VehicleSelect placeholder="请选择车辆" />,
  },
  {
    label: '司机',
    name: 'driverId',
    children: <DriverSelect placeholder="请选择司机" />,
  },
];

const Index = (props) => {
  const { source = 'default' } = props;
  const crudRef = useRef();
  const [mode, setMode] = useState('list');
  const [selectedKeys, setSelectedKeys] = useState([]);
  // const [record, setRecord] = useState();
  const [recordIndex, setRecordIndex] = useState();
  const [dataSource, setDataSource] = useState([]);
  const { materialTypeMap, materialTypeOptions } = useMaterial();

  // 批量交票表单
  const [returnTicketForm] = Form.useForm();
  // 批量结算表单
  const [balanceForm] = Form.useForm();
  // 批量发快递
  const [expressForm] = Form.useForm();
  const getList = async (params) => {
    const res = await request({
      url: {
        default: '/datas/weight/list',
        user: '/datas/weight/user/upload/list',
        driver: '/datas/weight/driver/upload/list',
        unbound: '/datas/weight/none/trip/list',
      }[source],
      method: 'GET',
      custom: true,
      params: params,
    });
    setDataSource(res?.data || []);
    return {
      total: res?.total,
      data: res?.data || [],
      // data: [{}],
    };
  };

  const deleteRow = (id) => {
    const ids = id ? [id] : selectedKeys;
    Modal.confirm({
      title: `确认删除所选数据?`,
      onOk: async () => {
        await request({
          url: '/datas/weight/delete',
          method: 'POST',
          data: { ids },
        });
        message.success('操作成功');
        crudRef.current?.reload()?.then?.((res) => {
          if ((recordIndex || 0) + 1 > res?.data?.length) {
            setMode('list');
          }
        });
        setSelectedKeys([]);
      },
    });
  };

  const generateTrip = async (weightId) => {
    await request({
      url: '/datas/weight/build/trip',
      method: 'GET',
      params: { weightId },
    });
    message.success('操作成功');
    crudRef.current?.reload?.();
  };

  // 批量交票功能
  const batchReturnTicket = () => {
    if (selectedKeys.length === 0) {
      message.warning('请先选择要交票的数据');
      return;
    }

    Modal.confirm({
      title: `批量交票 (已选择 ${selectedKeys.length} 条数据)`,
      width: 500,
      content: (
        <Form
          form={returnTicketForm}
          layout="vertical"
          initialValues={{
            returnCompany: 1, // 默认是
            returnDate: dayjs(), // 默认今日
          }}
        >
          <Form.Item
            label="已交票"
            name="returnCompany"
            rules={[{ required: true, message: '请选择交票状态' }]}
          >
            <Select options={BOOLEAN_OPTIONS} />
          </Form.Item>
          <Form.Item
            label="交票日期"
            name="returnDate"
            rules={[{ required: true, message: '请选择交票日期' }]}
          >
            <DatePicker style={{ width: '100%' }} format="YYYY-MM-DD" />
          </Form.Item>
        </Form>
      ),
      onOk: async () => {
        try {
          const values = await returnTicketForm.validateFields();
          await request({
            url: '/datas/weight/return/company/update',
            method: 'POST',
            data: {
              ids: selectedKeys,
              returnCompany: values.returnCompany,
              returnDate: values.returnDate.format('YYYY-MM-DD'),
            },
          });
          message.success('批量交票成功');
          crudRef.current?.reload();
          setSelectedKeys([]);
        } catch (error) {
          console.error('批量交票失败:', error);
        }
      },
      onCancel: () => {
        returnTicketForm.resetFields();
      },
    });
  };

  // 批量结算功能
  const batchBalance = () => {
    if (selectedKeys.length === 0) {
      message.warning('请先选择要结算的数据');
      return;
    }

    Modal.confirm({
      title: `批量结算 (已选择 ${selectedKeys.length} 条数据)`,
      width: 500,
      content: (
        <Form
          form={balanceForm}
          layout="vertical"
          initialValues={{
            balancePrice: 1, // 默认是
            balanceDate: dayjs(), // 默认今日
          }}
        >
          <Form.Item
            label="已结算"
            name="balancePrice"
            rules={[{ required: true, message: '请选择结算状态' }]}
          >
            <Select options={BOOLEAN_OPTIONS} />
          </Form.Item>
          <Form.Item
            label="结算日期"
            name="balanceDate"
            rules={[{ required: true, message: '请选择结算日期' }]}
          >
            <DatePicker style={{ width: '100%' }} format="YYYY-MM-DD" />
          </Form.Item>
        </Form>
      ),
      onOk: async () => {
        try {
          const values = await balanceForm.validateFields();
          await request({
            url: '/datas/weight/balance/update',
            method: 'POST',
            data: {
              ids: selectedKeys,
              balancePrice: values.balancePrice,
              balanceDate: values.balanceDate.format('YYYY-MM-DD'),
            },
          });
          message.success('批量结算成功');
          crudRef.current?.reload();
          setSelectedKeys([]);
        } catch (error) {
          console.error('批量结算失败:', error);
        }
      },
      onCancel: () => {
        balanceForm.resetFields();
      },
    });
  };

  // 批量发快递功能
  const batchExpress = () => {
    if (selectedKeys.length === 0) {
      message.warning('请先选择要发快递的数据');
      return;
    }

    Modal.confirm({
      title: `批量发快递 (已选择 ${selectedKeys.length} 条数据)`,
      width: 500,
      content: (
        <Form
          form={expressForm}
          layout="vertical"
          initialValues={{
            express: 1, // 默认是
            expressDate: dayjs(), // 默认今日
          }}
        >
          <Form.Item
            label="已发快递"
            name="express"
            rules={[{ required: true, message: '请选择发快递状态' }]}
          >
            <Select options={BOOLEAN_OPTIONS} />
          </Form.Item>
          <Form.Item
            label="发送日期"
            name="expressDate"
            rules={[{ required: true, message: '请选择发送日期' }]}
          >
            <DatePicker style={{ width: '100%' }} format="YYYY-MM-DD" />
          </Form.Item>
        </Form>
      ),
      onOk: async () => {
        try {
          const values = await expressForm.validateFields();
          await request({
            url: '/datas/weight/express/update',
            method: 'POST',
            data: {
              ids: selectedKeys,
              express: values.express,
              expressDate: values.expressDate.format('YYYY-MM-DD'),
            },
          });
          message.success('批量发快递成功');
          crudRef.current?.reload();
          setSelectedKeys([]);
        } catch (error) {
          console.error('批量发快递失败:', error);
        }
      },
      onCancel: () => {
        expressForm.resetFields();
      },
    });
  };

  const columns = [
    {
      title: '序号',
      fixed: 'left',
      width: 65,
      render: (text, record, index) => index + 1,
    },
    {
      title: '线路名称',
      dataIndex: 'lineName',
      width: 280,
      fixed: 'left',
    },
    {
      title: '车牌号',
      dataIndex: 'license',
      width: 120,
      fixed: 'left',
    },
    {
      title: '卸车磅单号',
      dataIndex: 'unloadWeightCode',
      width: 150,
      fixed: 'left',
    },
    {
      title: '卸车司机',
      dataIndex: 'unloadDriver',
      width: 150,
    },
    {
      title: '卸车司机电话',
      dataIndex: 'unloadPhone',
      width: 150,
    },
    {
      title: '组织',
      dataIndex: 'groupName',
      width: 220,
    },
    // {
    //   title: '线路',
    //   dataIndex: 'lineName',
    //   width: 180,
    // },

    {
      title: '装车司机',
      dataIndex: 'loadDriver',
      width: 150,
    },
    {
      title: '装车司机电话',
      dataIndex: 'loadPhone',
      width: 150,
    },

    {
      title: '物料类型',
      dataIndex: 'type',
      width: 100,
      render: (text) => materialTypeMap[text] || text,
    },
    {
      title: '客户名称',
      dataIndex: 'customerName',
      width: 150,
    },
    {
      title: '结算客户',
      dataIndex: 'settleCustomer',
      width: 150,
    },
    {
      title: '装车磅单号',
      dataIndex: 'loadWeightCode',
      width: 150,
    },
    {
      title: '装车时间',
      dataIndex: 'loadTime',
      width: 180,
    },
    {
      title: '装车毛重',
      dataIndex: 'loadEmptyWeight',
      width: 100,
    },
    {
      title: '装车皮重',
      dataIndex: 'loadTotalWeight',
      width: 100,
    },
    {
      title: '装车净重',
      dataIndex: 'loadWeight',
      width: 100,
    },
    {
      title: '装车费用（元）',
      dataIndex: 'loadPrice',
      width: 140,
    },

    {
      title: '卸车时间',
      dataIndex: 'unloadTime',
      width: 180,
    },
    {
      title: '卸车毛重',
      dataIndex: 'unloadEmptyWeight',
      width: 100,
    },
    {
      title: '卸车皮重',
      dataIndex: 'unloadTotalWeight',
      width: 100,
    },
    {
      title: '卸车净重',
      dataIndex: 'unloadWeight',
      width: 100,
    },
    {
      title: '磅差（吨或方）',
      dataIndex: 'discrepancyWeight',
      width: 140,
    },
    {
      title: '合理损耗（吨或方）',
      dataIndex: 'standardLossWeight',
      width: 160,
    },
    {
      title: '扣损重量（吨或方）',
      dataIndex: 'lossWeight',
      width: 160,
    },
    {
      title: '损耗金额（元）',
      dataIndex: 'lossPrice',
      width: 140,
    },
    {
      title: '卸车费用（元）',
      dataIndex: 'unloadPrice',
      width: 140,
    },
    {
      title: '路桥费用（元）',
      dataIndex: 'roadPrice',
      width: 140,
    },
    {
      title: 'ETC费用（元）',
      dataIndex: 'etcPrice',
      width: 140,
    },
    {
      title: '司机薪金（元）',
      dataIndex: 'driverPrice',
      width: 140,
    },
    {
      title: '轮胎损耗（元）',
      dataIndex: 'tyrePrice',
      width: 140,
    },
    {
      title: '信息费（元）',
      dataIndex: 'infoPrice',
      width: 140,
    },
    {
      title: '篷布费（元）',
      dataIndex: 'tarpaulinPrice',
      width: 140,
    },
    {
      title: '过磅费（元）',
      dataIndex: 'passWeightPrice',
      width: 140,
    },
    {
      title: '上车台费（元）',
      dataIndex: 'upCarPrice',
      width: 140,
    },
    {
      title: '下车台费（元）',
      dataIndex: 'downCarPrice',
      width: 140,
    },
    {
      title: '充电费（元）',
      dataIndex: 'chargePrice',
      width: 140,
    },
    {
      title: '交警罚款（元）',
      dataIndex: 'trafficTicket',
      width: 140,
    },
    {
      title: '维修费（元）',
      dataIndex: 'repairPrice',
      width: 140,
    },
    {
      title: '其他费用（元）',
      dataIndex: 'otherPrice',
      width: 140,
    },
    {
      title: '总支出（元）',
      dataIndex: 'totalPrice',
      width: 140,
    },
    {
      title: '线路运价（元/吨）',
      dataIndex: 'linePrice',
      width: 150,
    },
    {
      title: '任务营收（元）',
      dataIndex: 'taskPrice',
      width: 140,
    },
    {
      title: '结算金额（元）',
      dataIndex: 'settlement',
      width: 140,
    },
    {
      title: '营收毛利（元）',
      dataIndex: 'grossProfit',
      width: 140,
    },
    {
      title: '毛利率（%）',
      dataIndex: 'grossProfitRate',
      width: 120,
    },
    ...{
      default: [
        {
          title: '已交票',
          dataIndex: 'returnCompany',
          width: 80,
          render: (text) => BOOLEAN_MAP[text],
        },
        {
          title: '交票日期',
          dataIndex: 'returnDate',
          width: 130,
        },
        {
          title: '已结算',
          dataIndex: 'balancePrice',
          width: 80,
          render: (text) => BOOLEAN_MAP[text],
        },
        {
          title: '结算日期',
          dataIndex: 'balanceDate',
          width: 130,
        },
        {
          title: '已发快递',
          dataIndex: 'express',
          width: 100,
          render: (text) => BOOLEAN_MAP[text],
        },
        {
          title: '发送日期',
          dataIndex: 'expressDate',
          width: 130,
        },
      ],
      user: [],
      driver: [],
      unbound: [],
    }[source],
    {
      title: '用户名',
      dataIndex: 'username',
      width: 100,
    },
    {
      title: '上传时间',
      dataIndex: 'time',
      width: 180,
    },
    {
      title: '备注',
      dataIndex: 'remark',
      width: 150,
    },
    {
      title: '趟次编号',
      dataIndex: 'tripId',
      width: 200,
      render: (text, record, index) =>
        text ? (
          <a
            title="点击查看趟次详情"
            onClick={() => {
              setRecordIndex(index);
              setMode('tripDetail');
            }}
          >
            {text}
          </a>
        ) : (
          '-'
        ),
    },
    {
      title: '操作',
      dataIndex: 'weightId',
      width: 150,
      fixed: 'right',
      render: (text, record, index) => {
        return (
          <Space>
            {source !== 'unbound' && (
              <>
                <a
                  onClick={() => {
                    // setRecord(record);
                    setRecordIndex(index);
                    setMode('edit');
                  }}
                >
                  编辑
                </a>
                <a
                  onClick={() => {
                    deleteRow(record.weightId);
                  }}
                >
                  删除
                </a>
              </>
            )}
            {source === 'unbound' && (
              <a
                onClick={() => {
                  generateTrip(text);
                }}
              >
                生成趟次
              </a>
            )}
            <a
              onClick={() => {
                // setRecord(record);
                setRecordIndex(index);
                setMode('detail');
              }}
            >
              详情
            </a>
          </Space>
        );
      },
    },
  ];

  const fields = [
    ...{
      default: [
        {
          label: '组织',
          name: 'groupId',
          children: <GroupTreeSelect placeholder="请选择" />,
        },
        {
          label: '线路',
          name: 'lineId',
          children: <LineSelect placeholder="请选择" />,
        },
        {
          label: '物料类型',
          name: 'type',
          children: (
            <Select placeholder="请选择" options={materialTypeOptions} />
          ),
        },
        {
          label: '磅单号',
          name: 'weightCode',
          children: <Input placeholder="请输入" />,
        },
        {
          label: '车辆',
          name: 'vehicleId',
          children: <VehicleSelect placeholder="请选择" />,
        },
        {
          label: '司机',
          name: 'driverId',
          children: <DriverSelect placeholder="请选择" />,
        },
        {
          label: '已交票',
          name: 'returnCompany',
          children: <Select placeholder="请选择" options={BOOLEAN_OPTIONS} />,
        },
        {
          label: '已结算',
          name: 'balancePrice',
          children: <Select placeholder="请选择" options={BOOLEAN_OPTIONS} />,
        },
        {
          label: '已发快递',
          name: 'express',
          children: <Select placeholder="请选择" options={BOOLEAN_OPTIONS} />,
        },
        {
          label: '时间类型',
          name: 'timeType',
          children: (
            <Select
              placeholder="请选择时间类型"
              options={[
                { label: '卸货时间', value: 0 },
                { label: '上传时间', value: 1 },
              ]}
            />
          ),
        },
      ],
      user: [],
      driver: ADDITIONAL_FIELDS,
      unbound: ADDITIONAL_FIELDS.filter((item) => item.name === 'groupId'),
    }[source],
    {
      label: '开始时间',
      name: 'fromTime',
      children: (
        <DatePicker
          allowClear={false}
          showTime
          placeholder="请选择开始时间"
          format="YYYY-MM-DD HH:mm:ss"
        />
      ),
    },
    {
      label: '结束时间',
      name: 'toTime',
      children: (
        <DatePicker
          allowClear={false}
          showTime
          placeholder="请选择结束时间"
          format="YYYY-MM-DD HH:mm:ss"
        />
      ),
    },
  ];

  const handleExport = async () => {
    const params = crudRef.current?.getParams();
    const res = await request({
      url: '/datas/weight/export/list',
      method: 'GET',
      params,
    });
    window.open(res);
  };

  return (
    <>
      <Crud
        ref={crudRef}
        rowKey="weightId"
        queryFormProps={{
          labelCol: 7,
          initialValues: {
            default: {
              fromTime: dayjs().startOf('day'),
              toTime: dayjs().endOf('day'),
              timeType: 0,
            },
            user: {
              fromTime: dayjs().startOf('day'),
              toTime: dayjs().endOf('day'),
            },
            driver: {
              fromTime: dayjs().startOf('day'),
              toTime: dayjs().endOf('day'),
            },
            unbound: {
              fromTime: dayjs().subtract(29, 'day').startOf('day'),
              toTime: dayjs().endOf('day'),
            },
          }[source],
        }}
        fields={fields}
        columns={columns}
        request={getList}
        transformParams={(params) => {
          return {
            ...params,
            size: ['user', 'driver'].includes(source) ? 0 : params.size,
            fromTime: params?.fromTime?.format('YYYY-MM-DD HH:mm:ss'),
            toTime: params?.toTime?.format('YYYY-MM-DD HH:mm:ss'),
          };
        }}
        toolbar={
          <>
            {source === 'default' && (
              <Button
                type="primary"
                icon={<PlusOutlined />}
                onClick={() => setMode('add')}
              >
                新增
              </Button>
            )}
            {source !== 'unbound' && (
              <Button
                icon={<DeleteOutlined />}
                disabled={selectedKeys.length === 0}
                onClick={() => deleteRow()}
              >
                批量删除
              </Button>
            )}
            {source === 'default' && (
              <Button
                icon={<FileTextOutlined />}
                disabled={selectedKeys.length === 0}
                onClick={batchReturnTicket}
              >
                批量交票
              </Button>
            )}
            {source === 'default' && (
              <Button
                icon={<DollarOutlined />}
                disabled={selectedKeys.length === 0}
                onClick={batchBalance}
              >
                批量结算
              </Button>
            )}
            {source === 'default' && (
              <Button
                icon={<TruckOutlined />}
                disabled={selectedKeys.length === 0}
                onClick={batchExpress}
              >
                批量发快递
              </Button>
            )}
            {source === 'default' && (
              <Button
                type="primary"
                icon={<DownloadOutlined />}
                onClick={handleExport}
              >
                导出
              </Button>
            )}
          </>
        }
        tableProps={{
          pagination: ['user', 'driver'].includes(source)
            ? false
            : {
                defaultPageSize: 200,
              },
          rowSelection: {
            selectedRowKeys: selectedKeys,
            onChange: (selectedRowKeys) => {
              setSelectedKeys(selectedRowKeys);
            },
          },
          // rowClassName: (record) => {
          //   return record.state !== 0 ? 'highlight-row' : '';
          // },
        }}
        // toolbar={
        //   <>
        //     <Button
        //       type="primary"
        //       icon={<DownloadOutlined />}
        //       onClick={handleExport}
        //     >
        //       导出
        //     </Button>
        //   </>
        // }
      />
      <Save
        source={source}
        open={mode === 'edit' || mode === 'add'}
        record={dataSource?.[recordIndex]}
        numberStep={`${recordIndex + 1}/${dataSource.length}`}
        delBtnProps={{
          onClick: () => {
            deleteRow(dataSource?.[recordIndex]?.weightId);
          },
        }}
        preBtnProps={{
          disabled: recordIndex === 0,
          onClick: () => {
            setRecordIndex((_value) => _value - 1);
          },
        }}
        nextBtnProps={{
          disabled: recordIndex === dataSource.length - 1,
          onClick: () => {
            setRecordIndex((_value) => _value + 1);
          },
        }}
        saveGoOnBtnProps={{
          style:
            recordIndex < dataSource.length - 1
              ? undefined
              : {
                  display: 'none',
                },
        }}
        onCancel={() => {
          // setRecord();
          setRecordIndex();
          setMode('list');
        }}
        onOk={(goOn) => {
          // setRecord();
          if (goOn) {
            if (source === 'default') {
              setRecordIndex((_val) => {
                if (_val + 1 > dataSource.length) {
                  setMode('list');
                  return;
                }
                return _val + 1;
              });
            }
          } else {
            setRecordIndex();
            setMode('list');
          }
          crudRef.current?.reload();
        }}
      />
      <Detail
        source={source}
        open={mode === 'detail'}
        record={dataSource?.[recordIndex]}
        numberStep={`${recordIndex + 1}/${dataSource.length}`}
        onCancel={() => {
          setRecordIndex();
          setMode('list');
        }}
        preBtnProps={{
          disabled: recordIndex === 0,
          onClick: () => {
            setRecordIndex((_value) => _value - 1);
          },
        }}
        nextBtnProps={{
          disabled: recordIndex === dataSource.length - 1,
          onClick: () => {
            setRecordIndex((_value) => _value + 1);
          },
        }}
      />
      <TripDetail
        open={mode === 'tripDetail'}
        record={dataSource?.[recordIndex]}
        onCancel={() => {
          setRecordIndex();
          setMode('list');
        }}
      />
    </>
  );
};

export default Index;
